import {Image, StyleSheet, View, Text, TouchableOpacity, TextInput, ScrollView} from 'react-native';
import {Stack, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';
import { Ionicons } from '@expo/vector-icons';
import React, {useEffect, useState} from "react";
import Checkbox from "expo-checkbox";
import PickerModal from "@/components/MultiColumnPickerModal";
import MultiColumnPickerModal from "@/components/MultiColumnPickerModal";
import createTicketIcon from "@/assets/images/releaseImg/createTicketIcon.png"
import {format} from "date-fns";
import {showToast} from "@/utils/rootToast";
import {addPhone} from "@/store/slices/loginSlice";
import {useDispatch, useSelector} from "react-redux";
import {AppDispatch, RootState} from "@/store";
import { setTicketData, updateTicketData } from "@/store/slices/createActiveSilce"



export default function createTicketScreen() {

    const router = useRouter();
    const [active, setActive] = useState(0)
    const [pickerVisile, setPickerVisile] = useState(false);
    const [inputData, setInputData] = useState<any>({});
    const [showSelectDate, setShowSelectDate] = useState(false);
    const [activityTime, setActivityTime] = useState("");
    const [startTime, setStartTime] = useState<any>("");
    const [endTime, setEndTime] = useState<any>("");
    const [buyCheck, setBuyCheck] = useState(false);
    const [ticketValidity, setTicketValidity] = useState(false);
    const [fulterModal, setFulterModal] = useState(false);
    const [fulterTime, setFulterTime] = useState("");
    const [startFulterTime, setStartFulterTime] = useState<any>("");
    const [endFulterTime, setEndFulterTime] = useState<any>("");

    const dispatch = useDispatch<AppDispatch>();
    const createActive = useSelector((state: RootState) => state.createActive);


    useEffect(() => {

      if (createActive?.editTicketSetting) {
          createActive.ticketData.forEach((item: any, index: number) => {
              if (createActive.editTicketIndex == index) {
                  console.log('item', item);
                  const obj = {
                      ticketName: item.ticketName,
                      singleNum: item.singleNum + "",
                      quantity: item.quantity + "",
                      price: item.price + "",
                      description: item.description,
                  };
                  if (item.price > 0) {
                      setActive(1);
                  };
                  setInputData(obj);
                  setStartFulterTime(item.bookStartTime);
                  setEndFulterTime(item.bookEndTime);
                  setStartTime(item.validStartTime);
                  setEndTime(item.validEndTime)
              };
          })
      };
    }, []);


    const onChangeInputValue = function (key, val) {
        const objData = {
            ...inputData,
            [key]: val,
        };
        setInputData(objData)
    };


    const options = [
        { label: "周二", value: "周二" },
        { label: "周三", value: "周三" },
        { label: "周四", value: "周四" },
        { label: "周五 上午", value: "周五 上午" },
        { label: "周五 下午", value: "周五 下午" },
        { label: "周四", value: "周四" },
        { label: "周五 上午", value: "周五 上午" },
        { label: "周五 下午", value: "周五 下午" },
        { label: "周四", value: "周四" },
        { label: "周五 上午", value: "周五 上午" },
        { label: "周五 下午", value: "周五 下午" },
        { label: "周四", value: "周四" },
        { label: "周五 上午", value: "周五 上午" },
        { label: "周五 下午", value: "周五 下午" },
        { label: "周四", value: "周四" },
        { label: "周五 上午", value: "周五 上午" },
        { label: "周五 下午", value: "周五 下午" },
    ];

    const save = function () {
        console.log('inputData', inputData);
        if (!inputData.ticketName) {
            return showToast("请填写票种名称");
        };

        if (!inputData.singleNum) {
            return showToast("请输入单票人数");
        } else {
            if (isNaN(Number(inputData.singleNum))) {
                return showToast("请输入正确单票人数");
            };
        };

        if (!inputData.quantity) {
            return showToast("请输入票种数量");
        } else {
            if (isNaN(Number(inputData.quantity))) {
                return showToast("请输入正确票种数量")
            };
        };

        if (active == 1) {
            if (!inputData.price) {
                return showToast("请输入票种价格");
            } else {
                if (isNaN(Number(inputData.price))) {
                    return showToast("请输入正确票种价格")
                };
            }
        };

        if (!buyCheck && (!startFulterTime || !endFulterTime)) {
            return showToast("请选择可订购日期")
        };

        if (!ticketValidity && (!startTime || !endTime)) {
            return showToast("请选择可订购日期")
        };

        // if (!inputData.description) {
        //     return showToast("请填写票种说明")
        // };

        const data = {
            ticketName: inputData.ticketName,
            singleNum: Number(inputData.singleNum),
            quantity: Number(inputData.quantity),
            description: inputData.description,
            isOnSale: 0,
        };

        console.log('startFulterTime', startFulterTime);


        if (active == 0) {
            Reflect.set(data, "price", 0)
        } else {
            Reflect.set(data, "price", Number(inputData.price))
        };

        if (!buyCheck) {
            Reflect.set(data, 'bookStartTime', startFulterTime);
            Reflect.set(data, 'bookEndTime', endFulterTime)
        };

        if (!ticketValidity) {
            Reflect.set(data, 'validStartTime', startTime);
            Reflect.set(data, 'validEndTime', endTime)
        };


        if (buyCheck) {
            Reflect.set(data, 'bookStartTime',format(new Date(), "yyyy-MM-dd 00:00:00"));
            Reflect.set(data, 'bookEndTime', createActive.inputData.durationEndTime)
        };

        if (ticketValidity) {
            Reflect.set(data, 'validStartTime', format(new Date(), "yyyy-MM-dd 00:00:00"));
            Reflect.set(data, 'validEndTime', createActive.inputData.durationEndTime)
        };

        if (createActive.ticketSettingStatus == 'create') {
            dispatch(setTicketData({ ticketData: data }));
        } else if (createActive.ticketSettingStatus == 'update') {
            dispatch(updateTicketData({ ticketItem: data }));
        };




        router.push("/createActivity/ticketSetting")
        console.log('data', data);
    };

    const activeBtn = function () {
        return inputData.ticketName &&
                inputData.singleNum &&
                inputData.quantity &&
                (active == 1 ? inputData.price : true ) &&
                (!buyCheck ? (startFulterTime && endFulterTime) : true) &&
                (!ticketValidity ? (startTime && endTime) : true)
    };


    return (
        <View style={{ height: "100%", backgroundColor: "#F7F7F7" }}>
            <Stack.Screen
                options={{
                    title: '设置你的票种', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#FFF', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                }}
            />
            <View style={styles.createTicketHeader}>
                <TouchableOpacity onPress={() => setActive(0)}>
                    <View style={[ active == 0 ? styles.headerItem : ""]}>
                        <Text style={[active == 0 ? styles.activeColor : ""]}>
                            免费
                        </Text>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => setActive(1)}>
                    <View style={[ active == 1 ? styles.headerItem : ""]}>
                        <Text style={[active == 1 ? styles.activeColor : ""]} >
                            收费
                        </Text>
                    </View>
                </TouchableOpacity>
            </View>
            <ScrollView>
                <View style={styles.createTicketContainer}>

                    <View style={styles.createTickerBody}>
                        <View style={styles.createTicketItem}>
                            <Text>票种名称</Text>
                            <View>
                                <TextInput placeholder="请输入票种名称" value={inputData?.ticketName} onChangeText={(val) => onChangeInputValue("ticketName", val)} />
                            </View>
                        </View>
                        <View style={styles.createTicketItem}>
                            <Text>单票人数</Text>
                            <View>
                                <TextInput placeholder="1-10人" value={inputData?.singleNum} onChangeText={(val) => onChangeInputValue("singleNum", val)} />
                            </View>
                        </View>
                        {
                            active == 1 && (
                                <View style={styles.createTicketItem}>
                                    <Text>票种价格</Text>
                                    <View>
                                        <TextInput placeholder="请输入票种价格" value={inputData?.price} onChangeText={(val) => onChangeInputValue("price", val)} />
                                    </View>
                                </View>
                            )
                        }
                        <View style={styles.createTicketItem}>
                            <Text>票种数量</Text>
                            <View>
                                <TextInput placeholder="请输入票种数量" value={inputData?.quantity} onChangeText={(val) => onChangeInputValue("quantity", val)} />
                            </View>
                        </View>
                        <View style={styles.createTicketItem}>
                            <Text>可订购日期</Text>
                            <View style={{ flexDirection: "row", alignItems: "center" }}>
                                {
                                    buyCheck && (
                                        <TouchableOpacity onPress={() => setBuyCheck(false)}>
                                            <View style={styles.createSuccess}>
                                                <Image source={createTicketIcon} style={{ width: "100%", height: "100%" }}/>
                                            </View>
                                        </TouchableOpacity>
                                    )
                                }
                                {
                                    !buyCheck && (
                                        <TouchableOpacity onPress={() => setBuyCheck(true)}>
                                            <View style={styles.createUnSuccess}>
                                            </View>
                                        </TouchableOpacity>
                                    )
                                }
                                <Text>默认为活动结束前</Text>
                            </View>
                        </View>
                        {
                            !buyCheck && (
                                <View style={[styles.createTicketItem, { borderBottomWidth: 0 }]}>
                                    <Text>时间</Text>
                                    <View style={styles.timeRight}>
                                        <TouchableOpacity>
                                            {
                                                startFulterTime && (
                                                    <TouchableOpacity onPress={() => setFulterModal(true)}>
                                                        <Text style={styles.begin}>{ format(startFulterTime, "MM / dd HH:mm") }</Text>
                                                    </TouchableOpacity>
                                                )
                                            }
                                            {
                                                !startFulterTime && (
                                                    <TouchableOpacity onPress={() => setFulterModal(true)}>
                                                        <Text style={styles.begin}>开始售票时间</Text>
                                                    </TouchableOpacity>
                                                )
                                            }
                                        </TouchableOpacity>
                                        <View style={styles.timeCut}></View>
                                        <TouchableOpacity>
                                            {
                                                endFulterTime && (
                                                    <TouchableOpacity onPress={() => setFulterModal(true)}>
                                                        <Text style={styles.begin}>{ format(endFulterTime, "MM / dd HH:mm") }</Text>
                                                    </TouchableOpacity>
                                                )
                                            }
                                            {
                                                !endFulterTime && (
                                                    <TouchableOpacity onPress={() => setFulterModal(true)}>
                                                        <Text style={styles.begin}>结束售票时间</Text>
                                                    </TouchableOpacity>
                                                )
                                            }
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            )
                        }
                        <View style={styles.createTicketItem}>
                            <Text>票卷有效期</Text>
                            <View style={{ flexDirection: "row", alignItems: "center" }}>
                                {
                                    ticketValidity && (
                                        <TouchableOpacity onPress={() => setTicketValidity(false)}>
                                            <View style={styles.createSuccess}>
                                                <Image source={createTicketIcon} style={{ width: "100%", height: "100%" }}/>
                                            </View>
                                        </TouchableOpacity>
                                    )
                                }
                                {
                                    !ticketValidity && (
                                        <TouchableOpacity onPress={() => setTicketValidity(true)}>
                                            <View style={styles.createUnSuccess}>
                                            </View>
                                        </TouchableOpacity>
                                    )
                                }
                                <Text>默认为活动结束前</Text>
                            </View>
                        </View>
                        {
                            !ticketValidity && (
                                <View style={[styles.createTicketItem, { borderBottomWidth: 0 }]}>
                                    <Text>时间</Text>
                                    <View style={styles.timeRight}>
                                        <TouchableOpacity>
                                            {
                                                startTime && (
                                                    <TouchableOpacity onPress={() => setShowSelectDate(true)}>
                                                        <Text style={styles.begin}>{ format(startTime, "MM / dd HH:mm") }</Text>
                                                    </TouchableOpacity>
                                                )
                                            }
                                            {
                                                !startTime && (
                                                    <TouchableOpacity onPress={() => setShowSelectDate(true)}>
                                                        <Text style={styles.begin}>开始时间</Text>
                                                    </TouchableOpacity>
                                                )
                                            }
                                        </TouchableOpacity>
                                        <View style={styles.timeCut}></View>
                                        <TouchableOpacity>
                                            {
                                                endTime && (
                                                    <TouchableOpacity onPress={() => setShowSelectDate(true)}>
                                                        <Text style={styles.begin}>{ format(endTime, "MM / dd HH:mm") }</Text>
                                                    </TouchableOpacity>
                                                )
                                            }
                                            {
                                                !endTime && (
                                                    <TouchableOpacity onPress={() => setShowSelectDate(true)}>
                                                        <Text style={styles.begin}>结束时间</Text>
                                                    </TouchableOpacity>

                                                )
                                            }
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            )
                        }
                    </View>
                    <View style={styles.ticketDescWrap}>
                        <View>
                            <Text>票种说明(选填)</Text>
                        </View>
                        <View style={styles.descContent}>
                            <TextInput multiline={true} placeholder="限200个字，可为空" style={styles.descInpt} value={inputData?.description} onChangeText={(val) => onChangeInputValue("description", val)} />
                        </View>
                    </View>
                </View>


                <PickerModal
                    visible={pickerVisile}
                    onConfirm={() => {
                        console.log('ok')
                    }}
                    onCancel={() => {
                        console.log('onCancel')
                    }}
                    options={options}
                />

                <MultiColumnPickerModal
                    visible={showSelectDate}
                    onCancel={() => setShowSelectDate(false)}
                    startValue={startTime}
                    endValue={endTime}
                    onConfirm={(time, startT, endT) => {
                        setActivityTime(time);
                        console.log("startT", startT);
                        setStartTime(startT);
                        setEndTime(endT);
                    }}
                />


                <MultiColumnPickerModal
                    visible={fulterModal}
                    startValue={startFulterTime}
                    endValue={endFulterTime}
                    onCancel={() => setFulterModal(false)}
                    onConfirm={(time, startT, endT) => {
                        setFulterTime(time);
                        console.log("startT", startT);
                        setStartFulterTime(startT);
                        setEndFulterTime(endT);
                    }}
                />
                {
                    !activeBtn() && (
                        <View style={styles.saveBtnWrap}>
                            <TouchableOpacity onPress={save}>
                                <View style={styles.saveBtn}>
                                    <Text style={styles.saveBtnText}>保存</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    )
                }

                {
                    activeBtn() && (
                        <View style={styles.saveBtnWrap}>
                            <TouchableOpacity onPress={save}>
                                <View style={styles.activeSaveBtn}>
                                    <Text style={styles.saveBtnText}>保存</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    )
                }
            </ScrollView>
        </View>
    );
}

const styles = StyleSheet.create({
    createTicketContainer: {
        flex:1,
    },
    createTicketHeader: {
        flexDirection: "row",
        backgroundColor: "#fff",
        paddingHorizontal: 145,
        justifyContent: "space-between"
    },
    headerItem: {
        borderBottomWidth: 3,
        paddingBottom: 2,
        borderColor: "#EC6138",
        borderRadius: 1,
    },
    activeColor: {
        color: "#EC6138"
    },
    createTickerBody: {
        marginHorizontal: 12,
        marginTop: 12,
        backgroundColor: "#fff",
        borderRadius: 10,
        // paddingTop: 12,
        paddingLeft: 12,
        paddingRight: 12,
    },
    createTicketItem: {
        flexDirection: "row",
        justifyContent: "space-between",
        borderBottomWidth: 0.3,
        borderColor: "#E4E6EC",
        paddingBottom: 12,
        marginTop: 17,
        // marginBottom: 17,
    },
    agreeCircle: {
        color: "#333",
        borderRadius: 50,
        borderWidth: 1,
        width: 13,
        height: 13,
        marginRight: 2,
        borderColor: "#E4E6EC"
    },
    timeRight: {
        flexDirection: "row",
        alignItems: "center",
    },
    timeCut: {
        width: 20,
        height: 1,
        marginRight: 21,
        backgroundColor: "#2A2B30"
    },
    begin: {
        color: "#9C9EAC",
        marginRight: 24,
    },
    end: {
        color: "#9C9EAC",
        marginLeft: 24,
    },
    ticketDescWrap: {
        marginHorizontal: 12,
        backgroundColor: "#fff",
        marginTop: 12,
        borderRadius: 10,
        padding: 12,
    },
    descContent: {
        marginTop: 10,
    },
    descInpt: {
        height: 120,
        backgroundColor: "#F7F8F9",
        borderRadius: 6,
        padding: 12,
    },
    saveBtnWrap: {
        paddingTop: 12,
        paddingBottom: 23,
        backgroundColor: "#fff",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    saveBtn: {
        width: scaleSize(351),
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "#E4E6EC",
        paddingVertical: 12,
        borderRadius: 19,
    },
    activeSaveBtn: {
        width: scaleSize(351),
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "#EC6138",
        paddingVertical: 12,
        borderRadius: 19,
    },
    saveBtnText: {
        color: "#fff",
    },
    createSuccess: {
        width: 14,
        height: 14,
        marginRight: 6,
    },
    createUnSuccess: {
        width: 14,
        height: 14,
        borderWidth: 1,
        borderRadius: 20,
        borderColor: "#E4E6EC",
        marginRight: 6,
    },
});
